//获取应用实例
const app = getApp();
// 引入AES.js
var baseJs = require("../../common/base.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: baseJs.imgUrl,
    orderNum: {},
    orderData: [],
    showType: '待支付',
    pageIndex: 1,
    state: '',
    fiveData: [{
        'title': '待付款',
        'active': true,
        'src0': "../../images/icon/order_1.png",
        'src1': "../../images/icon/order1.png",
        'showType': "待支付"
      },
      {
        'title': '待兑换',
        'active': false,
        'src0': "../../images/icon/order_2.png",
        'src1': "../../images/icon/order2.png",
        'showType': "已支付"
      },
      {
        'title': '交易完',
        'active': false,
        'src0': "../../images/icon/order_5.png",
        'src1': "../../images/icon/order5.png",
        'showType': "交易结束"
      }
    ],
    // 去付款
    payFlag: true,
    createOrderData: {},
    payDetail: "",
    payMoney: 0,
    // 余额/微信
    payType: "",
    // 
    uid: "",
    userType: "",
    // 输入支付密码
    //是否展示密码输入层
    showPayPwdInput: false,
    //输入的密码
    payPasswords: "",
    //文本框焦点
    payFocus: true,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      uid: wx.getStorageSync('uid'),
      userType: wx.getStorageSync('userType')
    })
    this.GetExchangeOrderStateNum();
    this.GetOrderList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.data.pageIndex++;
    this.GetOrderList();
  },

  //显示支付密码输入层
  showInputLayer: function() {
    this.setData({
      showPayPwdInput: true,
      payFocus: true
    });
  },
  //隐藏支付密码输入层
  cancelInputPasswords: function() {
    var val = this.data.payPasswords;
    this.setData({
      showPayPwdInput: false,
      payFocus: false,
      payPasswords: ''
    });

  },
  // 获取焦点
  getFocus: function() {
    this.setData({
      payFocus: true
    });
  },
  //输入密码,监听
  inputPwd: function(e) {
    this.setData({
      payPasswords: e.detail.value
    });
  },
  //输入密码 确定 
  surePasswords: function() {
    var thst = this;
    var uid = this.data.uid;
    var payPasswords = this.data.payPasswords;
    var orderNumber = this.data.orderNumber;
    var createOrderData = this.data.createOrderData;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=CheckMyTradePassword&UID=" + uid + "&TradePassword=" + payPasswords),
      success: function(res) {
        var json = JSON.parse(baseJs.decryUrl(res.data));
        console.log(json);
        if (json.ResultFlag == 1) {
          wx.request({
            url: baseJs.api + baseJs.encryUrl("method=PayOrder&OrderNumber=" + createOrderData.OrderNumber + "&PayMa=" + parseFloat(createOrderData.useNeedPayMa).toFixed(2) + "&PayMaCounterFee=" + parseFloat(createOrderData.useNeedPayMaFee).toFixed(2) + "&PayRMB=" + parseFloat(createOrderData.useNeedBuxianRMB).toFixed(2) + "&PayAccountRMB=0&PayRMBCounterFee=0&IsAllPay=1"),
            success: function(res) {
              var json = JSON.parse(baseJs.decryUrl(res.data))
              console.log(json);
              if (json.ResultFlag == 1) {
                that.setData({
                  pageIndex: 1,
                  orderData: [],
                })
                that.GetExchangeOrderStateNum();
                that.GetOrderList();
              } else {
                wx.showToast({
                  title: json.ResultMsg,
                  icon: 'none',
                  duration: 2000
                });
              }
            }
          })
        } else {
          wx.showToast({
            title: json.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
  },
  // 
  showTypeTap: function(e) {
    console.log(e);
    var fiveData = this.data.fiveData;
    var showType = e.currentTarget.dataset.showtype;
    for (var i = 0, len = fiveData.length; i < len; ++i) {
      if (fiveData[i].showType == showType) {
        fiveData[i].active = true;
      } else {
        fiveData[i].active = false
      }
    }
    this.setData({
      fiveData: fiveData,
      showType: showType
    })
    this.data.pageIndex = 1;
    this.data.orderData = [];
    this.GetOrderList();
    console.log(showType);
  },
  // 得到订单状态所有的个数
  GetExchangeOrderStateNum: function() {
    var that = this;
    var uid = this.data.uid;
    var orderNum = this.data.orderNum;
    var fiveData = this.data.fiveData;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetExchangeOrderStateNum&UID=" + uid + "&IsBusinessOrder=0"),
      success: function(res) {
        orderNum = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        fiveData[0].num = orderNum.waitPay;
        fiveData[1].num = orderNum.waitshipped;
        fiveData[2].num = orderNum.finished;
        that.setData({
          orderNum: orderNum,
          fiveData: fiveData,
        })
        console.log(orderNum);
      }
    })
  },
  //加载订单列表
  GetOrderList: function() {
    var that = this;
    var uid = this.data.uid;
    var showType = this.data.showType;
    var pageIndex = this.data.pageIndex;
    var orderData = this.data.orderData;
    if (pageIndex == 1) {
      wx.showLoading({
        title: '加载中',
      })
    }
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetOrderList&UID=" + uid + "&Type=1&DeliverGoods=1&IsBusinessOrder=0&PageSize=10&PageIndex=" + pageIndex + "&OrderState=" + showType),
      success: function(res) {
        var json = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        for (var i = 0; i < json.length; i++) {
          orderData.push(json[i])
        }
        that.setData({
          orderData: orderData,
        })
        if (json.length == 10) {
          that.setData({
            state: 'loadMore',
          })
        } else if (json.length == 0 && pageIndex == 1) {
          that.setData({
            state: 'noData',
          })
        } else if (json.length < 10) {
          that.setData({
            state: 'noMore',
          })
        } else if (json.length == 0 && pageIndex > 1) {
          that.setData({
            state: 'noMore',
          })
        }
        wx.hideLoading();
      }
    })
  },
  // 取消订单
  cancelOrderTap: function(e) {
    console.log(e);
    var that = this;
    var uid = this.data.uid;
    var orderData = this.data.orderData;
    wx.showModal({
      title: '提示',
      content: '确认取消该订单吗？',
      success: function(res) {
        if (res.confirm) {
          // console.log('用户点击确定');
          wx.request({
            url: baseJs.api + baseJs.encryUrl("method=DeleteOrder&OrderNumber=" + e.currentTarget.dataset.orderid),
            success: function(res) {
              console.log(JSON.parse(baseJs.decryUrl(res.data)));
              if (JSON.parse(baseJs.decryUrl(res.data)).ResultFlag == 1) {
                wx.showToast({
                  title: JSON.parse(baseJs.decryUrl(res.data)).ResultMsg,
                  icon: 'none',
                  duration: 2000
                });
                orderData.splice(e.currentTarget.dataset.index, 1);
                that.setData({
                  orderData: orderData
                })
                that.GetExchangeOrderStateNum();
              } else {

              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    })
  },
  // 退款
  refund: function(e) {
    var that = this;
    var payDetail = this.data.payDetail;
    wx.navigateTo({
      url: "/packageA/refund/refund?orderNum=" + e.currentTarget.dataset.ordernum + "&payDetail=" + payDetail
    })

  },
  // 删除订单
  delOrderTap: function(e) {
    var that = this;
    var orderData = this.data.orderData;
    wx.showModal({
      title: '提示',
      content: '确认删除该订单吗？',
      success: function(res) {
        if (res.confirm) {
          // console.log('用户点击确定');
          wx.request({
            url: baseJs.api + baseJs.encryUrl("method=DeleteOrder&OrderNumber=" + e.currentTarget.dataset.orderid),
            success: function(res) {
              if (JSON.parse(baseJs.decryUrl(res.data)).ResultFlag == 1) {
                wx.showToast({
                  title: JSON.parse(baseJs.decryUrl(res.data)).ResultMsg,
                  icon: 'none',
                  duration: 2000
                });
                orderData.splice(e.currentTarget.dataset.index, 1);
                that.setData({
                  orderData: orderData
                })
                that.GetExchangeOrderStateNum();
              } else {

              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    })
  },
  // 弹出付款
  goPay0: function(e) {
    var that = this;
    var uid = this.data.uid;
    var payFlag = this.data.payFlag;
    var payDetail = this.data.payDetail;
    var payMoney = this.data.payMoney;
    var createOrderData = this.data.createOrderData;
    wx.showLoading({
      title: '正在生成订单',
    })
    setTimeout(function() {
      wx.hideLoading()
    }, 2000)
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetNeedPayData&orderNumber=" + e.currentTarget.dataset.ordernum + "&UID=" + uid + "&SJID=" + e.currentTarget.dataset.businessid),
      success: function(res) {
        createOrderData = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        console.log(JSON.parse(baseJs.decryUrl(res.data)));
        if (createOrderData.StockNum <= 0) {
          wx.showToast({
            title: "该商品已无库存！",
            icon: 'none',
            duration: 2000
          });
        } else {
          payMoney = parseFloat(createOrderData.useNeedAllPayRMB).toFixed(2);
          payDetail = parseFloat(createOrderData.useNeedPayMa).toFixed(2) + "M + " + parseFloat(createOrderData.useNeedBuxianRMB).toFixed(2) + "元（补现） + " + parseFloat(createOrderData.useNeedPayMaFee).toFixed(2) + "元（M管理费） + " + parseFloat(createOrderData.Youfei).toFixed(2) + "元（邮费）";
          wx.showToast({
            title: "订单生成成功",
            icon: 'none',
            duration: 1000
          });
          that.setData({
            payFlag: false,
            payDetail: payDetail,
            payMoney: payMoney,
            createOrderData: createOrderData
          });
        }
      }
    })

  },
  goPay1: function() {
    this.setData({
      payFlag: !this.data.payFlag,
    });
  },
  //余额或微信 
  radioChange: function(e) {
    var payType = this.data.payType;
    payType = e.detail.value
    this.setData({
      payType: payType,
    });
  },
  // 去付款
  goPay: function() {
    var that = this;
    var createOrderData = this.data.createOrderData;
    var payType = this.data.payType;
    var pageIndex = this.data.pageIndex;
    var orderData = this.data.orderData;
    if (payType == '') {
      wx.showToast({
        title: "请选择支付方式！",
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    this.setData({
      payFlag: true
    })
    if (payType == "1") {
      that.setData({
        showPayPwdInput: true,
        payFocus: true
      })
    } else {
      wx.request({
        url: baseJs.api + baseJs.encryUrl("method=PayOrder&OrderNumber=" + createOrderData.OrderNumber + "&PayMa=" + parseFloat(createOrderData.useNeedPayMa).toFixed(2) + "&PayMaCounterFee=" + parseFloat(createOrderData.useNeedPayMaFee).toFixed(2) + "&PayRMB=" + parseFloat(createOrderData.useNeedBuxianRMB).toFixed(2) + "&PayAccountRMB=0&PayRMBCounterFee=0&IsAllPay=2"),
        success: function(res) {
          var json = JSON.parse(baseJs.decryUrl(res.data));
          // console.log("method=PayOrder&OrderNumber=" + createOrderData.OrderNumber + "&PayMa=" + parseFloat(createOrderData.useNeedPayMa).toFixed(2) + "&PayMaCounterFee=" + parseFloat(createOrderData.useNeedPayMaFee).toFixed(2) + "&PayRMB=" + parseFloat(createOrderData.useNeedBuxianRMB).toFixed(2) + "&PayAccountRMB=0&PayRMBCounterFee=0&IsAllPay=" + payType);
          console.log(json);
          if (json.ResultFlag == "1") {
            // wx.requestPayment({
            //   timeStamp: json.ResultData.timestamp,
            //   nonceStr: json.ResultData.nonce_str,
            //   package: 'prepay_id=' + json.ResultData.prepay_id,
            //   signType: 'MD5',
            //   paySign: json.ResultData.sign,
            //   success(res) {
            //     console.log(res);
            //     that.setData({
            //       pageIndex: 1,
            //       orderData: [],
            //     })
            //     that.GetExchangeOrderStateNum();
            //     that.GetOrderList();
            //   },
            //   fail(res) {
            //     console.log(res);
            //     wx.showToast({
            //       title: res.err_desc,
            //       icon: 'none',
            //       duration: 2000
            //     });
            //   }
            // })
          }else{
            wx.showToast({
              title: json.ResultMsg,
              icon: 'none',
              duration: 2000
            });
          }

        }
      })
    }


  },
  // 申请核销applyHeXiao
  applyHeXiao: function(e) {
    var that = this;
    var uid = this.data.uid;
    var orderData = this.data.orderData;
    wx.showModal({
      title: '提示',
      content: '是否申请核销订单？',
      success: function(res) {
        if (res.confirm) {
          // console.log('用户点击确定');
          wx.request({
            url: baseJs.api + baseJs.encryUrl("method=PlaceBusinessFinishExchangeOrder&UID=" + uid + "&OrderId=" + e.currentTarget.dataset.orderid),
            success: function(res) {
              if (JSON.parse(baseJs.decryUrl(res.data)).ResultFlag == 1) {
                wx.showToast({
                  title: JSON.parse(baseJs.decryUrl(res.data)).ResultMsg,
                  icon: 'none',
                  duration: 2000
                });
                that.setData({
                  pageIndex: 1,
                  orderData: []
                })
                that.GetExchangeOrderStateNum();
                that.GetOrderList();
                that.setData({
                  orderData: orderData
                })
              } else {
                wx.showToast({
                  title: JSON.parse(baseJs.decryUrl(res.data)).ResultMsg,
                  icon: 'none',
                  duration: 2000
                });
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    })
  },
  // 

})